package pl.szpadel.android.gadu.packets;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;

/// Packet with incoming message
public class RecvMsg80 extends ReceivedPacket {
	
	public static final String TAG = "AndroidGaduService";
	
	public int sender;
	public int seq;
	public int time;
	public int cls;
	//public int offset_plain;
	//public int offsert_attributes;
	public String htmlMessage;
	public String plainMessage;
	

	public RecvMsg80(Header hdr, InputStream stream) throws IOException {
		super(hdr, stream);
	}

	protected RecvMsg80(Header hdr, ReadableByteChannel channel) throws IOException {
		super(hdr, channel);
	}

	@Override
	protected void readFromBuffer(ByteBuffer buffer) {
		sender = buffer.getInt();
		seq = buffer.getInt();
		time = buffer.getInt();
		cls = buffer.getInt();
		
		final int BASE_OFFSET = 24;
		
		int offset_plain = buffer.getInt();
		int offset_attr = buffer.getInt();
		
		int htmlLen = offset_plain - BASE_OFFSET;
		int plainLen = offset_attr - offset_plain;
		
		//Log.d(TAG, "offset plain: " + offset_plain + ", ofsert_attr: " + offset_attr + " bytes remaining:" + buffer.remaining());
		try {
			if (htmlLen > 0) {
				byte htmlMsg[] = new byte[htmlLen-1];
				buffer.get(htmlMsg);
				buffer.get(); // get null terminator
				htmlMessage = new String(htmlMsg, "UTF-8");
			};
			if (plainLen > 0) {
				byte plainMsg[] = new byte[plainLen-1];
				buffer.get(plainMsg);
				buffer.get(); // get null terminator
				plainMessage = new String(plainMsg, "CP1250");
			}
		} catch (UnsupportedEncodingException e) {
			htmlMessage = new String();
			plainMessage = new String();
		}
	}
	
	/// to string
	public String toString() {
		return "RecvMsg80 [ uin=" + sender + "\n    html(" + htmlMessage + "),\n    plain(" + plainMessage + ") ]";
	}

}
